﻿using ComicBookApp.Data.DataAdapters.Adapters;
using ComicBookApp.Data.DataAdapters.Interfaces;
using ComicBookApp.DataModels;
using ComicBookApp.Web.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ComicBookApp.Web.Controllers
{
    [Authorize]
    public class ComicBookController : Controller
    {

        IComicBookAppAdapter _adapter;

        public ComicBookController()
        {
            _adapter = new ComicBookAppAdapter();
        }
        public ComicBookController(ComicBookAppAdapter adapter)
        {
            _adapter = adapter;
        }


        // GET: ComicBook
        [AllowAnonymous]
        public ActionResult Index()
        {
            List<ComicBook> comics = _adapter.GetAllComicBooks();

            return View(comics);
        }
        public ActionResult Add()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Add(ComicBook comic)
        {
            comic = _adapter.CreateComicBook(comic);
            return RedirectToAction("Detail/" + comic.Id);
        }
        public ActionResult Detail(int id = 0)
        {
            if (id <= 0)
            {
                return RedirectToAction("Index");
            }
            if (User.IsInRole("Admin"))
            {
                ComicBookDetailVM bucket = new ComicBookDetailVM();
                bucket.ComicBook = _adapter.GetComicBook(id);
                bucket.Characters = _adapter.GetCharactersForComic(bucket.ComicBook);
                bucket.Creators = _adapter.GetCreatorsForComic(bucket.ComicBook);

                return View(bucket);
            }
            return RedirectToAction("Index");

        }
        public ActionResult Edit(int id)
        {
            if (id <= 0)
            {
                return RedirectToAction("Index");
            }

            ComicBookDetailVM bucket = new ComicBookDetailVM();
            bucket.ComicBook = _adapter.GetComicBook(id);
            bucket.Characters = _adapter.GetCharactersForComic(bucket.ComicBook);
            return View(bucket);
        }
        [HttpPost]
        public ActionResult Edit(ComicBook comic)
        {
            comic = _adapter.UpdateComicBook(comic);
            return RedirectToAction("Detail/" + comic.Id);
        }

        [HttpPost]
        public ActionResult Delete(int id)
        {
            ComicBook comic = _adapter.DeleteComicBook(id);
            return RedirectToAction("Index");
        }
    }
}